<template>
  <div class="theme-settings-page">
    <van-nav-bar
      title="主题设置"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <div class="settings-section">
      <div class="section-title">主题模式</div>
      <div class="theme-mode-options">
        <div 
          class="theme-mode-item" 
          :class="{ active: preferences.theme === 'light' }"
          @click="updateTheme('light')"
        >
          <div class="theme-preview light-theme">
            <div class="preview-header"></div>
            <div class="preview-content"></div>
          </div>
          <div class="theme-name">浅色模式</div>
        </div>
        
        <div 
          class="theme-mode-item" 
          :class="{ active: preferences.theme === 'dark' }"
          @click="updateTheme('dark')"
        >
          <div class="theme-preview dark-theme">
            <div class="preview-header"></div>
            <div class="preview-content"></div>
          </div>
          <div class="theme-name">深色模式</div>
        </div>
      </div>
    </div>
    
    <div class="settings-section">
      <div class="section-title">主题颜色</div>
      <div class="theme-color-options">
        <div 
          v-for="color in themeColors" 
          :key="color.value"
          class="color-item"
          :class="{ active: preferences.themeColor === color.value }"
          :style="{ backgroundColor: color.color }"
          @click="updateThemeColor(color.value)"
        ></div>
        
        <div 
          class="color-item custom-color"
          :class="{ active: preferences.themeColor === 'custom' }"
          @click="showColorPicker = true"
        >
          <van-icon name="add" size="20" />
        </div>
      </div>
    </div>
    
    <div class="settings-section">
      <div class="section-title">自定义背景</div>
      <div class="custom-bg-options">
        <div class="bg-preview" @click="selectBackgroundImage">
          <img v-if="preferences.customBgImage" :src="preferences.customBgImage" alt="自定义背景" />
          <div v-else class="empty-bg">
            <van-icon name="photo-o" size="24" />
            <span>选择背景图片</span>
          </div>
        </div>
        
        <div class="bg-actions" v-if="preferences.customBgImage">
          <van-button type="danger" size="small" icon="delete-o" @click="removeBackgroundImage">
            移除背景
          </van-button>
        </div>
      </div>
    </div>
    
    <!-- 颜色选择器弹窗 -->
    <van-popup
      v-model:show="showColorPicker"
      position="bottom"
      round
      :style="{ height: '50%' }"
    >
      <div class="color-picker-container">
        <div class="popup-header">
          <div class="popup-title">选择自定义颜色</div>
          <van-icon name="cross" @click="showColorPicker = false" />
        </div>
        
        <div class="color-picker-content">
          <div class="color-preview" :style="{ backgroundColor: customColor }"></div>
          
          <div class="color-inputs">
            <van-field
              v-model="customColor"
              label="颜色值"
              placeholder="#1989fa"
              :rules="[{ pattern: /^#[0-9A-Fa-f]{6}$/, message: '请输入有效的十六进制颜色值' }]"
            />
          </div>
          
          <div class="preset-colors">
            <div 
              v-for="color in presetColors" 
              :key="color"
              class="preset-color-item"
              :style="{ backgroundColor: color }"
              @click="customColor = color"
            ></div>
          </div>
          
          <div class="color-picker-actions">
            <van-button 
              type="primary" 
              block 
              @click="applyCustomColor"
              :disabled="!/^#[0-9A-Fa-f]{6}$/.test(customColor)"
            >
              应用颜色
            </van-button>
          </div>
        </div>
      </div>
    </van-popup>
    
    <!-- 文件选择器（隐藏） -->
    <input 
      type="file" 
      ref="fileInput" 
      accept="image/*" 
      style="display: none;" 
      @change="onFileSelected" 
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '../../store/user'

const router = useRouter()
const userStore = useUserStore()
const preferences = computed(() => userStore.preferences)

// 主题颜色选项
const themeColors = [
  { value: 'blue', color: 'var(--theme-blue)', label: '蓝色' },
  { value: 'green', color: 'var(--theme-green)', label: '绿色' },
  { value: 'red', color: 'var(--theme-red)', label: '红色' },
  { value: 'orange', color: 'var(--theme-orange)', label: '橙色' },
  { value: 'purple', color: 'var(--theme-purple)', label: '紫色' },
  { value: 'pink', color: 'var(--theme-pink)', label: '粉色' },
  { value: 'cyan', color: 'var(--theme-cyan)', label: '青色' }
]

// 自定义颜色相关
const showColorPicker = ref(false)
const customColor = ref('#1989fa')
const presetColors = [
  '#1989fa', '#07c160', '#ee0a24', '#ff976a', 
  '#8a2be2', '#ff6699', '#1abc9c', '#3498db',
  '#9b59b6', '#f1c40f', '#e67e22', '#e74c3c'
]

// 文件选择相关
const fileInput = ref(null)

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 更新主题模式
const updateTheme = (theme) => {
  userStore.updateTheme(theme)
  showToast(`已切换到${theme === 'dark' ? '深色' : '浅色'}模式`)
}

// 更新主题颜色
const updateThemeColor = (color) => {
  if (color === 'custom') {
    showColorPicker.value = true
    return
  }
  
  userStore.updateThemeColor(color)
  showToast(`已更新主题颜色`)
}

// 应用自定义颜色
const applyCustomColor = () => {
  if (!/^#[0-9A-Fa-f]{6}$/.test(customColor.value)) {
    showToast('请输入有效的十六进制颜色值')
    return
  }
  
  userStore.setCustomThemeColor(customColor.value)
  showToast('已应用自定义颜色')
  showColorPicker.value = false
}

// 选择背景图片
const selectBackgroundImage = () => {
  fileInput.value.click()
}

// 文件选择回调
const onFileSelected = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    showToast('请选择图片文件')
    return
  }
  
  // 检查文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    showToast('图片大小不能超过2MB')
    return
  }
  
  // 读取文件为Data URL
  const reader = new FileReader()
  reader.onload = (e) => {
    userStore.setCustomBackgroundImage(e.target.result)
    showToast('已设置自定义背景')
  }
  reader.readAsDataURL(file)
  
  // 清空文件选择器，以便再次选择同一文件
  event.target.value = ''
}

// 移除背景图片
const removeBackgroundImage = () => {
  userStore.setCustomBackgroundImage('')
  showToast('已移除背景图片')
}

// 组件挂载时，如果有自定义颜色，则显示
onMounted(() => {
  if (preferences.value.themeColor === 'custom') {
    // 获取当前自定义颜色
    const customColorValue = getComputedStyle(document.documentElement).getPropertyValue('--theme-custom').trim()
    if (customColorValue) {
      customColor.value = customColorValue
    }
  }
})
</script>

<style lang="scss" scoped>
.theme-settings-page {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: calc(var(--tabbar-height) + 20px);
  
  .settings-section {
    margin-top: 12px;
    background-color: var(--background-color-light);
    padding: 16px;
    
    .section-title {
      font-size: 16px;
      font-weight: 500;
      color: var(--text-color);
      margin-bottom: 16px;
    }
    
    .theme-mode-options {
      display: flex;
      justify-content: space-around;
      
      .theme-mode-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 120px;
        
        &.active {
          .theme-preview {
            border: 2px solid var(--primary-color);
          }
          
          .theme-name {
            color: var(--primary-color);
          }
        }
        
        .theme-preview {
          width: 100%;
          height: 180px;
          border-radius: 8px;
          overflow: hidden;
          border: 2px solid transparent;
          margin-bottom: 8px;
          
          &.light-theme {
            background-color: #f7f8fa;
            
            .preview-header {
              height: 40px;
              background-color: #1989fa;
            }
            
            .preview-content {
              height: calc(100% - 40px);
              background-color: #ffffff;
            }
          }
          
          &.dark-theme {
            background-color: #121212;
            
            .preview-header {
              height: 40px;
              background-color: #1989fa;
            }
            
            .preview-content {
              height: calc(100% - 40px);
              background-color: #1e1e1e;
            }
          }
        }
        
        .theme-name {
          font-size: 14px;
          color: var(--text-color);
          margin-top: 8px;
        }
      }
    }
    
    .theme-color-options {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      
      .color-item {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        cursor: pointer;
        position: relative;
        
        &.active::after {
          content: '';
          position: absolute;
          top: -4px;
          left: -4px;
          right: -4px;
          bottom: -4px;
          border: 2px solid var(--primary-color);
          border-radius: 50%;
        }
        
        &.custom-color {
          background-color: #f5f5f5;
          display: flex;
          justify-content: center;
          align-items: center;
          color: var(--text-color-tertiary);
          
          [data-theme='dark'] & {
            background-color: #2c2c2c;
          }
        }
      }
    }
    
    .custom-bg-options {
      .bg-preview {
        height: 160px;
        border-radius: 8px;
        overflow: hidden;
        background-color: var(--background-color);
        margin-bottom: 16px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .empty-bg {
          display: flex;
          flex-direction: column;
          align-items: center;
          color: var(--text-color-tertiary);
          
          span {
            margin-top: 8px;
            font-size: 14px;
          }
        }
      }
      
      .bg-actions {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
  
  .color-picker-container {
    padding: 16px;
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .popup-title {
        font-size: 18px;
        font-weight: 500;
      }
    }
    
    .color-picker-content {
      .color-preview {
        width: 100%;
        height: 80px;
        border-radius: 8px;
        margin-bottom: 16px;
      }
      
      .color-inputs {
        margin-bottom: 16px;
      }
      
      .preset-colors {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        margin-bottom: 24px;
        
        .preset-color-item {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          cursor: pointer;
        }
      }
      
      .color-picker-actions {
        margin-top: 16px;
      }
    }
  }
}
</style> 